import 'package:flutter/material.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/components/TabContainerWidget/TabContainerWidget.dart';
import 'package:orginone/components/TabContainerWidget/types.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/provider/session.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/main.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/date_util.dart';
import 'package:orginone/utils/log/log_util.dart';

import '../../components/ListSearchWidget/ListSearchWidget.dart';
import '../../components/PortalManagerWidget/portalrefresh_event.dart';
import '../../dart/base/common/commands.dart';

/// 沟通页面
class ChatPage extends StatefulWidget {
  TabContainerModel? relationModel;
  List<ISession>? datas;

  ChatPage({super.key, List<ISession>? datas}) {
    relationModel = null;
    dynamic params = RoutePages.getParentRouteParam();
    this.datas = datas ?? (params is List<ISession> ? params : null);
  }

  @override
  State<StatefulWidget> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final ScrollController scrollController = ScrollController();
  TabContainerModel? get relationModel => widget.relationModel;
  set relationModel(TabContainerModel? value) {
    widget.relationModel = value;
  }

  List<ISession>? get datas => widget.datas;

  IChatProvider? get chatProvider => relationCtrl.provider.chatProvider;
  List<ISession>? get chats => chatProvider?.chats ?? [];

  @override
  void initState() {
    // 事件监听器
    portalRefreshEventBus.on<PortalRefreshEvent>().listen(onPortalEvent);
    super.initState();
  }

  //监听Bus events
  void onPortalEvent(PortalRefreshEvent event) {
    command.emitter('chat', 'new');
  }

  @override
  Widget build(BuildContext context) {
    return CommandWidget<TabContainerWidget>(
        type: 'chat',
        cmd: 'new',
        builder: (context, args) {
          load(context);
          return TabContainerWidget(
            relationModel!,
          );
        });
  }

  void load(BuildContext context) {
    relationModel = TabContainerModel(
        title: "沟通",
        activeTabTitle: getActiveTabTitle(),
        tabItems: [
          createTabItemsModel(context, title: "最近"),
          createTabItemsModel(context, title: "常用"),
          createTabItemsModel(context, title: "@我"),
          createTabItemsModel(context, title: "好友"),
          createTabItemsModel(context, title: "群组"),
          createTabItemsModel(context, title: "同事"),
          createTabItemsModel(context, title: "单位"),
          // createTabItemsModel(title: "集群"),
        ]);
  }

  /// 获得激活页签
  getActiveTabTitle() {
    return RoutePages.getRouteDefaultActiveTab()?.firstOrNull;
  }

  TabItemsModel createTabItemsModel(
    BuildContext context, {
    required String title,
  }) {
    RxList<ISession> initDatas = RxList();

    return TabItemsModel(
        title: title,
        content: ListSearchWidget(
          initDatas: initDatas.value,
          onInitLoad: ([String? searchText]) async {
            if (null == datas) {
              initDatas.value = getSessionsByLabel(title, searchText??"");
            } else {
              initDatas.value = getSessionsByLabel(title, searchText??"", datas: datas) ?? [];
            }
            return initDatas.value;
          },
          scrollController: scrollController,
          getBadge: (dynamic data) {
            return data.noReadCount;
          },
          getAction: (dynamic data) {
            return Text(CustomDateUtil.getSessionTime(data.updateTime),
                style: XFonts.chatSMTimeTip, textAlign: TextAlign.right);
          },
          onTap: (dynamic data, List children) {
            XLogUtil.d('>>>>>>======点击了列表项 ${data.name}');
            if (data is ISession) {
              RoutePages.jumpChatSession(context: context, data: data);
            }
          },
        )
    );
  }

  // 根据标签获得沟通会话列表
  List<ISession> getSessionsByLabel(String label, String searchText, {List<ISession>? datas}) {
    datas ??= chats;
    if (label == "单位") {
      return datas
              ?.where((element) =>
                  (element.groupTags.contains(label) ||
                      element.groupTags.contains("群组") ||
                      element.groupTags.contains("部门")) && element.search(searchText))
              .toList() ??
          [];
    } else if (label == "集群") {
      return datas
              ?.where((element) =>
                  (element.groupTags.contains(label) ||
                      element.groupTags.contains("组织群")) && element.search(searchText))
              .toList() ??
          [];
    } else if (label == "最近") {
      return datas
              ?.where((element) => !element.groupTags.contains("组织群") && element.search(searchText))
              .toList() ??
          [];
    }
    return datas
            ?.where(
                (element) => label == '最近' || element.groupTags.contains(label))
            .toList() ??
        [];
  }
}
